using System;
using System.Collections;
using UnityEngine;

[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapons/Base Weapon", order = 1)]
public abstract class Weapon : ScriptableObject
{
    public string weaponName;
    public Sprite icon;
    public GameObject weaponPrefab;
    public float damage;
    public float fireRate;
    public int ammoCapacity;
    public int currentAmmo;
    public float reloadTime;

    [HideInInspector] public GameObject equippedInstance;
    [HideInInspector] public Transform firePoint;
    [HideInInspector] public float cooldownTimer;
    [HideInInspector] public bool isReloading;

    public virtual void Equip(Transform firePointTransform)
    {
        firePoint = firePointTransform;

        //
        if (equippedInstance != null)
            Destroy(equippedInstance);

        equippedInstance = Instantiate(weaponPrefab, firePoint);
        equippedInstance.transform.localPosition = Vector3.zero;
        equippedInstance.transform.localRotation = Quaternion.identity;
    }

    public virtual bool Attack()
    {
        //cooldownTimer = 0f;
        //
        if (cooldownTimer > 0 || isReloading || currentAmmo <= 0)
        {
            Debug.Log("Cannot Attack:"+ weaponName+" isReloading: " + isReloading + " currentAmmo<=0: " +(currentAmmo<=0) + " " + currentAmmo + " cooldownTimer<=0: " + (cooldownTimer>0) +" " + cooldownTimer);
            if (currentAmmo <= 0)
                StartReload();

            return false;
        }

        PerformAttack();
        currentAmmo--;
        cooldownTimer = 1f / fireRate;
        return true;
    }

    protected abstract void PerformAttack();

    public virtual void StartReload()
    {
        Debug.Log("Start Reload");
        //if (isReloading || currentAmmo == ammoCapacity) return;

        isReloading = true;
        {
            //GameManager.Instance.Invoke(nameof(FinishReload), reloadTime);
           GameManager.Instance.StartCoroutine(Reload());
        }
        EventManager.TriggerEvent(new WeaponReloadStartedEvent(this));
    }

    IEnumerator Reload()
    {
        Debug.Log("Reloading");
        yield return new WaitForSeconds(reloadTime);
        FinishReload();
    }

    private object FinishReload()
    {
        Debug.Log("Finish Reload");
        currentAmmo = ammoCapacity;
        isReloading = false;
        return null;
        //throw new NotImplementedException();
    }
}
